<template>
  <div class="canvas-tool">
    <div class="add-element-handler">
      <div
        class="handler-item group-btn"
        :class="{ active: isActive === 'system' }"
        :offset="10"
        @click="onSystem()"
        v-if="!isProposalLayout"
      >
        <IconLayers v-tooltip="$t('system')" />
        <div class="fosi_sty">{{ $t('system') }}</div>
      </div>
      <div
        class="handler-item group-btn"
        :class="{ active: isActive === 'equipment' }"
        :offset="10"
        @click="onEquipment()"
        v-if="!isProposalLayout"
      >
        <IconSwitchButton v-tooltip="$t('equipment')" />
        <div class="fosi_sty">{{ $t('equipment') }}</div>
      </div>
      <!-- Test -->
      <div class="handler-item group-btn" v-tooltip="$t('insertText')" @click="drawText()">
        <IconFontSize class="icon" :class="{ active: isActive === 'text' }" />
        <Popover
          trigger="click"
          v-model:value="textTypeSelectVisible"
          style="height: 100%"
          :offset="10"
          @click="isActive = 'text'"
          @on-close="isActive = ''"
        >
          <template #content>
            <PopoverMenuItem
              center
              @click="
                () => {
                  drawText();
                  textTypeSelectVisible = false;
                }
              "
            >
              <IconTextRotationNone /> {{ $t('horizontalText') }}
            </PopoverMenuItem>
            <PopoverMenuItem
              center
              @click="
                () => {
                  drawText(true);
                  textTypeSelectVisible = false;
                }
              "
            >
              <IconTextRotationDown /> {{ $t('verticalText') }}
            </PopoverMenuItem>
          </template>
          <IconDown class="arrow" />
        </Popover>
        <div class="fosi_sty" :class="{ active: isActive === 'text' }">
          {{ $t('insertText') }}
        </div>
      </div>
      <div
        class="handler-item group-btn"
        v-tooltip="$t('insertShape')"
        :offset="10"
        :class="{ active: isActive === 'shape' }"
      >
        <Popover
          trigger="click"
          style="height: 100%"
          v-model:value="shapePoolVisible"
          :offset="10"
          @click="isActive = 'shape'"
          @on-close="isActive = ''"
        >
          <template #content>
            <ShapePool @select="(shape) => drawShape(shape)" />
          </template>
          <IconGraphicDesign class="icon" />
        </Popover>
        <Popover
          trigger="click"
          v-model:value="shapeMenuVisible"
          style="height: 100%"
          :offset="10"
          @click="isActive = 'shape'"
          @on-close="isActive = ''"
        >
          <template #content>
            <PopoverMenuItem
              center
              @click="
                () => {
                  drawCustomShape();
                  shapeMenuVisible = false;
                }
              "
              >{{ $t('freeDrawing') }}</PopoverMenuItem
            >
          </template>
          <IconDown class="arrow" />
        </Popover>
        <div class="fosi_sty">{{ $t('insertShape') }}</div>
      </div>
      <FileInput class="handler-item" @change="(files) => insertImageElement(files)">
        <IconPicture v-tooltip="$t('insertImage')" />
        <div class="fosi_sty">{{ $t('insertImage') }}</div>
      </FileInput>
      <Popover
        class="handler-item"
        :class="{ active: isActive === 'line' }"
        trigger="click"
        v-model:value="linePoolVisible"
        :offset="10"
        @click="isActive = 'line'"
        @on-close="isActive = ''"
      >
        <template #content>
          <LinePool @select="(line) => drawLine(line)" />
        </template>
        <IconConnection v-tooltip="$t('insertLine')" />
        <div class="fosi_sty">{{ $t('insertLine') }}</div>
      </Popover>
      <!-- chart -->
      <Popover
        class="handler-item"
        trigger="click"
        v-model:value="chartPoolVisible"
        :offset="10"
        @click="(isActive = 'tubiao'), handleGetAnalysisData()"
        @on-close="isActive = '',quoteId = ''"
      >
        <template #content>
          <div style="width: 700px">
            <el-tabs v-model="activeName">
              <el-tab-pane :label="$t('charts.investmentAnalysis')" name="first">
                <el-row>
                  <el-col :span="24" style="display: flex; align-items: center; gap: 12px">
                    <el-select
                      v-model="quoteId"
                      filterable
                      style="margin-left: 10px;width:80%"
                      :teleported="false"
                      popper-class="down-popover"
                    >
                      <el-option
                        v-for="item in quotationList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>

                    <!-- 类型报价类型 -->
                    <div style="display: flex">
                      <el-tag v-show="equipType" type="primary" plain>{{
                        $t('investment.new_system_equipment')
                      }}</el-tag>
                      <el-tag  v-show="systemType" type="primary" plain>{{
                        $t('investment.reuse_old_equipment')
                      }}</el-tag>
                    </div>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <SystemAnalysisChart ref="systemAnalysis" v-if="systemType" :quoteId="quoteId" />
                    <EquipAnalysisChart ref="equipAnalysis" v-if="equipType" :quoteId="quoteId" />
                  </el-col>
                </el-row>
                <el-row></el-row>
              </el-tab-pane>
              <el-tab-pane :label="$t('charts.systemChart')" name="second">
                <ChartPool
                  @select="
                    (chart) => {
                      createChartElement(chart);
                      chartPoolVisible = false;
                      isActive = '';
                    }
                  "
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </template>
        <IconChartProportion v-tooltip="$t('insertChart')" :class="{ active: isActive === 'tubiao' }" />
        <div class="fosi_sty" :class="{ active: isActive === 'tubiao' }">
          {{ $t('insertChart') }}
        </div>
      </Popover>
      <Popover
        class="handler-item"
        trigger="click"
        v-model:value="tableGeneratorVisible"
        :offset="10"
        @click="isActive = 'table'"
        @on-close="isActive = ''"
      >
        <template #content>
          <TableGenerator
            @close="tableGeneratorVisible = false"
            @insert="
              ({ row, col }) => {
                createTableElement(row, col);
                tableGeneratorVisible = false;
                isActive = '';
              }
            "
          />
        </template>
        <IconInsertTable class="handler-item" :class="{ active: isActive === 'table' }" v-tooltip="$t('insertTable')" />
        <div class="fosi_sty" :class="{ active: isActive === 'table' }">
          {{ $t('insertTable') }}
        </div>
      </Popover>
      <div class="handler-item" :class="{ active: isActive === 'formula' }">
        <IconFormula
          v-tooltip="$t('insertFormula')"
          @click="
            () => {
              latexEditorVisible = true;
              isActive = 'formula';
            }
          "
        />
        <div class="fosi_sty">{{ $t('insertFormula') }}</div>
      </div>
      <!-- media -->
      <Popover
        class="handler-item"
        trigger="click"
        v-model:value="mediaInputVisible"
        :offset="10"
        @click="isActive = 'video'"
        @on-close="isActive = ''"
      >
        <template #content>
          <MediaInput
            @close="
              () => {
                mediaInputVisible = false;
                isActive = '';
              }
            "
            @insertVideo="
              (src) => {
                createVideoElement(src);
                mediaInputVisible = false;
                isActive = '';
              }
            "
            @insertAudio="
              (src) => {
                createAudioElement(src);
                mediaInputVisible = false;
                isActive = '';
              }
            "
          />
        </template>
        <IconVideoTwo class="handler-item" v-tooltip="$t('insertMedia')" :class="{ active: isActive === 'video' }" />
        <div class="fosi_sty" :class="{ active: isActive === 'video' }">
          {{ $t('insertMedia') }}
        </div>
      </Popover>

      <!-- ai -->
      <div class="handler-item" :class="{ active: isActive === 'ai' }" @click="handleClickAI">
        <IconBrain v-tooltip="$t('insertAi')" />
        <div class="fosi_sty">{{ $t('insertAi') }}</div>
      </div>
    </div>

    <teleport to="#viewport-background" v-if="magicButton.show">
      <MagicButton
        v-show="magicButton.show"
        class="magic-btn"
        :style="{
          position: 'absolute',
          left: magicButton.left,
          top: magicButton.top,
        }"
        @click="handleClickAI"
      >
        {{ $t('ai.ai_run') }}
      </MagicButton>
    </teleport>

    <Modal v-model:visible="latexEditorVisible" :width="880">
      <LaTeXEditor
        @close="
          () => {
            latexEditorVisible = false;
            isActive = '';
          }
        "
        @update="
          (data) => {
            createLatexElement(data);
            latexEditorVisible = false;
            isActive = '';
          }
        "
      />
    </Modal>

    <AiDrawer
      v-model="aiDrawerVisible"
      :content="textContent"
      :aiContent="textAiContent"
      @replace="replace"
      @close="closeDrawer"
    ></AiDrawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, reactive, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore, useProposalStore } from '@/store'
import { getImageDataURL } from '@/utils/image'
import { useI18n } from 'vue-i18n'
import type { ShapePoolItem } from '@/configs/shapes'
import type { LinePoolItem } from '@/configs/lines'
import useCreateElement from '@/hooks/useCreateElement'
import useSelectElement from '@/hooks/useSelectElement'

import AiDrawer from '@/components/AiDrawer.vue'
import ShapePool from './ShapePool.vue'
import LinePool from './LinePool.vue'
import ChartPool from './ChartPool.vue'
import TableGenerator from './TableGenerator.vue'
import MediaInput from './MediaInput.vue'
import LaTeXEditor from '@/components/LaTeXEditor/index.vue'
import FileInput from '@/components/FileInput.vue'
import Modal from '@/components/Modal.vue'
import Popover from '@/components/Popover.vue'
import PopoverMenuItem from '@/components/PopoverMenuItem.vue'
import message from '@/utils/message'
import MagicButton from '@/components/MagicButton.vue'
import SystemAnalysisChart from './components/SystemAnalysisChart.vue'
import EquipAnalysisChart from './components/equipAnalysisChart.vue'
import fetch from '@/api/fetch'

const mainStore = useMainStore()
const proposalStore = useProposalStore()
const activeName = ref<string>('first')

const { handleElement, handleElementId, canvasScale, showSelectPanel, showSearchPanel, showNotesPanel } =
  storeToRefs(mainStore)

const { isProposalLayoutCreate, isProposalLayoutEdit, isProposalLayoutView, projectId } = storeToRefs(proposalStore)

const {
  createImageElement,
  createChartElement,
  createTableElement,
  createLatexElement,
  createVideoElement,
  createAudioElement,
} = useCreateElement()

const { selectElement } = useSelectElement()

const { t } = useI18n()
const activeButton = ref('add') // 默认激活的按钮
const isProposalLayout = computed(() => {
  return isProposalLayoutCreate.value || isProposalLayoutEdit.value || isProposalLayoutView.value
})
const insertImageElement = (files: FileList) => {
  const imageFile = files[0]
  if (!imageFile) return
  getImageDataURL(imageFile).then((dataURL) => createImageElement(dataURL))
}

const shapePoolVisible = ref(false)
const linePoolVisible = ref(false)
const chartPoolVisible = ref(false)
const tableGeneratorVisible = ref(false)
const mediaInputVisible = ref(false)
const latexEditorVisible = ref(false)
const textTypeSelectVisible = ref(false)
const shapeMenuVisible = ref(false)
const aiDrawerVisible = ref(false)
const isActive = ref('')
const selectId = ref('')
const magicButton = ref({
  show: false,
  left: '45%',
  top: '10%',
})

/**
 * 报价单
 */
const quotationList = ref([])
// quoteType 报价类型 1.新增系统设备 Equip 2.沿用旧设备 System
const quoteType = ref(null)
const quoteId = ref('')
const equipAnalysis = ref(null)
const systemAnalysis = ref(null)

// 新增系统设备
const equipType = computed(() => {
  return quoteType.value === 1
})
// 沿用旧设备
const systemType = computed(() => {
  return quoteType.value === 2
})

const updateQuotaType = (quotaId) => {
  const quotation = quotationList.value.find((item) => item.value === quotaId)
  quotation && (quoteType.value = quotation.type)
  // quotePrice = quotation.quotePrice;
}

const handleGetAnalysisData = async () => {
  if (!projectId.value) return
  const { rows } = (await fetch.get('/system/investment/list?projectId=' + projectId.value)) as any
  quotationList.value = rows.map((item) => ({
    value: item.quoteId + '',
    label: item.quoteName,
    type: item.quoteType,
    quotePrice: item.quotePrice,
  }))
  // 默认选中第一个
  quotationList.value.length && (quoteId.value = quotationList.value[0].value)
}

watch(quoteId, async (val) => {
  updateQuotaType(val)

  await nextTick()

  if (val) {
    equipType.value && (await equipAnalysis.value.getList())
    systemType.value && (await systemAnalysis.value.getList())
  }
})

const emit = defineEmits<{
  (event: 'click', payload: string): void;
}>()


watch(isActive, () => {
  emit('click', isActive.value)
})

// 选中id时点击按钮会取消选中的元素导致拿不到数据，保留选中元素的id再次赋值
watch(handleElement, (val) => {
  // 包含 aiValue 时显示ai按钮
  const type = val?.type
  if (type === 'text' && Object.hasOwn(val, 'aiValue')) {
    const { left, top, width } = val
    magicButton.value.show = true
    magicButton.value.left = `calc(${left + width / 3}px * (${canvasScale.value}))`
    magicButton.value.top = `calc(${top}px * (${canvasScale.value}) - 10%)`
    selectId.value = handleElementId.value
  }
  else {
    setTimeout(() => {
      magicButton.value.show = false
    }, 110)
  }
})

const textContent = ref('')
const textAiContent = ref('')
const elementStyle = reactive({
  fontSize: '18px',
  fontWeight: false,
})
const handleClickAI = () => {
  selectElement(selectId.value)

  const type = handleElement.value?.type
  const hasAiValue = Object.hasOwn(handleElement.value || {}, 'aiValue')
  if (type !== 'text' || !hasAiValue) {
    return message.error(t('ai.warm_tips'))
  }
  const content = handleElement.value.content
  const aiContent = handleElement.value.aiValue

  aiDrawerVisible.value = true
  const parser = new DOMParser()
  const doc = parser.parseFromString(content, 'text/html')
  const html = doc.body.innerHTML
  elementStyle.fontSize = html.match(/font-size: (\d+)px;/)?.[1]
  // 是否使用strong标签
  elementStyle.fontWeight = html.includes('<strong>') || html.includes('<b>')

  textContent.value = doc.body.textContent
  textAiContent.value = aiContent
}

const replace = (text: string) => {
  const fontSizeStyle = `font-size: ${elementStyle.fontSize}px;`
  const content = elementStyle.fontWeight ? `<strong>${text}</strong>` : text
  const htmlString = `<div style="${fontSizeStyle}">${content}</div>`

  if (handleElement.value.type === 'text') {
    handleElement.value.content = htmlString
  }
}

// 直接在handleClickAI关关不掉,不知道为什么,感觉是传送门的问题
const closeDrawer = () => {
  magicButton.value.show = true
}
// 系统
const onSystem = () => {
  isActive.value = 'system'
}
// 设备
const onEquipment = () => {
  isActive.value = 'equipment'
}
// 绘制文字范围
const drawText = (vertical = false) => {
  mainStore.setCreatingElement({
    type: 'text',
    vertical,
  })
  isActive.value = ''
}

// 绘制形状范围
const drawShape = (shape: ShapePoolItem) => {
  mainStore.setCreatingElement({
    type: 'shape',
    data: shape,
  })
  shapePoolVisible.value = false
  isActive.value = ''
}
// 绘制自定义任意多边形
const drawCustomShape = () => {
  mainStore.setCreatingCustomShapeState(true)
  shapePoolVisible.value = false
}

// 绘制线条路径
const drawLine = (line: LinePoolItem) => {
  mainStore.setCreatingElement({
    type: 'line',
    data: line,
  })
  linePoolVisible.value = false
  isActive.value = ''
}

// 打开选择面板
const toggleSelectPanel = () => {
  mainStore.setSelectPanelState(!showSelectPanel.value)
}
const setActive = (button) => {
  activeButton.value = button
  // 在这里添加切换按钮时的逻辑
}
// 打开搜索替换面板
const toggleSraechPanel = () => {
  mainStore.setSearchPanelState(!showSearchPanel.value)
}

// 打开批注面板
const toggleNotesPanel = () => {
  mainStore.setNotesPanelState(!showNotesPanel.value)
}
</script>

<!-- el_option的样式被popover遮住了优先级没那么高,需要单独设置 -->
<style lang="scss" scoped>
.down-popover {
  z-index: 99999999 !important;
}
.active {
  color: #3170ff !important;
}

.canvas-tool {
  position: relative;
}

.add-element-handler {
  padding-bottom: 16px;
  width: 60px;

  .fosi_sty {
    font-size: 12px;
    // color: #333;
    text-align: center;
    position: absolute;
    top: 40px;
  }

  .handler-item {
    &:not(.group-btn):hover {
      background-color: #f1f1f1;
    }

    &.group-btn {
      &:hover {
        background-color: #f3f3f3;
      }

      .icon,
      .arrow {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .icon {
        &:hover {
          background-color: #e9e9e9;
        }

        &.active {
          color: $themeColor;
        }
      }

      .arrow {
        font-size: 12px;

        &:hover {
          background-color: #e9e9e9;
        }
      }
    }
  }
}

.handler-item {
  color: #333;
  height: 60px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  cursor: pointer;

  position: relative;

  &.disable {
    opacity: 0.5;
  }
}

.first-echart {
  width: 450px;
  display: flex;
  align-items: center;

  .select-input {
    width: 150px;
    margin-right: 20px;
  }

  .chart-container {
    display: flex;
    flex-direction: column;
  }

  .button-group {
    display: flex;
    gap: 10px;
  }

  .charts {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .chart {
    border: 1px solid #ccc;
    padding: 10px;
    width: 200px;
    height: 150px;
    background-color: #f0f0f0;
  }

  button {
    padding: 10px 20px;
    margin: 5px;
    border: none;
    background-color: #fff;
    color: #333;
    cursor: pointer;
  }

  button.active {
    background-color: #007bff;
    color: #fff !important;
  }
}
</style>
